import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Headers, Http } from '@angular/http';
import { AppConfig } from "../config";
import { Factory } from "../entity/factory.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class FactoryService {
  private readonly param = "factorys";
  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }
  constructor(
    private http: InterceptorService,
    private https: Http
  ) { }
  getFactory(): Promise<Factory[]> {
    //let url = `http://192.168.15.150:8585/webapi/v1/factorys`
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.json().data as Factory[])
      .catch(this.handleError);
  }
  create(factory: Factory): Promise<Factory> {
    return this.http.post(this.url, JSON.stringify(factory))
      .toPromise()
      .then(res => {
        try {
          let result = res.json();
          switch (result.code) {
            case "200":
              return result.data as Factory;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(factory: Factory): Promise<boolean> {
    //const url = `${this.url}`;
    //let url = `http://192.168.15.150:8585/webapi/v1/factorys`
    return this.http.put(this.url, JSON.stringify(factory))
      .toPromise()
      .then(response => {
        try {
          let result = response.json();
          switch (result.code) {
            case "200":
              return result;
            case "-1":
              throw new Error(result.message);
            case "8001":
              return result;
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }
  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }
  batchDelete(keyIds: number[]): Promise<any> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    // const apiUrl = `http://192.168.15.3:8585/webapi/v1/models?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response.json();
          switch (result.code) {
            case "200":
              return result;
            case "-1":
              throw new Error(result.message);
            case "8001":
              return result;
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }
  upFile(file) {
    var formData = new FormData();
    formData.append("file", file[0], file[0].name);
    return this.https.post(`${this.url}/uploadFiles`, formData)
      .toPromise()
      .then(res => {
        try {
          let result = res.json();
          switch (result.code) {
            case "200":
              return result.data as string;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }
  hasFactoryName(factoryName: string, factoryId: number): Observable<boolean> {
    //let url = `http://192.168.15.150:8585/webapi/v1/factorys/factoryName/${factoryName}/factoryId/${factoryId}`
    const url = `${this.url}/factoryName/${factoryName}/factoryId/${factoryId}`;
    return this.http.get(url).map(response => {
      let code = response.json().code;
      switch (code) {
        case "3001":
          return true;
        case "3002":
          return false;
      }

    }).catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}






// WEBPACK FOOTER //
// ./src/app/service/factory.service.ts